﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JsonContractResolverDemo;

public class NullJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        dynamic values = token.ToObject(objectType);
        return EmptyArrayToNull(objectType, values);
    }

    public override bool CanWrite => false;
    public override bool CanRead => true;

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        
    }
    private object? EmptyArrayToNull(Type objectType, dynamic values)
    {
        return values?.Count == 0 ? values : null;
    }
}